import axios from 'axios';
import { getToken } from '@/utils/storage';
import { toLogin } from '@/utils/toLogin';
import { CommonMessage } from './message';

// create an axios instance
const service = axios.create({
  baseURL: '/api', // api的base_url
  timeout: 120000, // request timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    // Do something before request is sent
    // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    config.headers['X-token'] = getToken();
    return config;
  },
  error => {
    // Do something with request error
    Promise.reject(error);
  }
);

// respone拦截器
service.interceptors.response.use(
  response => {
    /**
     * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
     * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
     */
    const res = response.data;
    if (res.code === '208') {
      let param = {
        message: 'userHasLogout',
      };
      window.parent.postMessage(JSON.stringify(param), '*');
      let message = res.msg || '您没有登录或操作超时,请重新登录!';
      CommonMessage(message);
      window.setTimeout(function() {
        // store.dispatch('FedLogOut').then(() => {
        toLogin();
        // })
        return false;
      }, 1000);
    }
    if (res.code === '202') {
      let msg = res.msg || '操作失败';
      CommonMessage(msg, 'warning');
      if (res.msg === 'token value is null') {
        window.setTimeout(function() {
          // store.dispatch('FedLogOut').then(() => {
          toLogin();
          // })
          return false;
        }, 1000);
      } else {
        return Promise.reject(res.msg);
      }
    }
    if (res.code === '204' || res.code === '206' || res.code === '210') {
      CommonMessage(res.msg);
      return Promise.reject(res.msg);
    }
    if (response.status !== 200) {
      CommonMessage(res.message);
    } else {
      return response;
    }
  },
  error => {
    if (!error.response) {
      CommonMessage('网络连接失败，请检查您的网络');
      return false;
    }
    if (error.request.status === 401) {
      let message = error.response.data.msg || '您没有登录或操作超时,请重新登录!';
      CommonMessage(message);
      window.setTimeout(function() {
        // store.dispatch('FedLogOut').then(() => {
        toLogin();
        // })
        return false;
      }, 1000);
    } else {
      CommonMessage(error.message || '服务器错误，请稍后重试');
    }
    return Promise.reject(error.message);
  }
);

export default service;
